﻿using System;
using System.Linq.Expressions;
using Library.Transactions;

namespace Library.Logic.Transactional
{
    internal class Scope : ITransaction<bool>
    {
        static Scope _true = new Scope(true);
        static Scope _false = new Scope(false);

        public static Scope True { get { return _true; } }
        public static Scope False { get { return _false; } }

        public static implicit operator bool(Scope scope)
        {
            return scope.value;
        }
        public static bool operator true(Scope scope)
        {
            return scope.value;
        }
        public static bool operator false(Scope scope)
        {
            return !scope.value;
        }

        protected Scope(bool value)
        {
            this.value = value;
        }

        bool value;
        public bool Value
        {
            get
            {
                return value;
            }
        }

        public virtual void Commit() { }

        public virtual void Dispose() { }
    }

    internal sealed class ScopeAction : Scope
    {
        public ScopeAction(bool value, Action rollback)
            : base(value)
        {
            this.rollback = rollback;
        }

        Action rollback;

        public override void Commit()
        {
            rollback = null;
        }
        public override void Dispose()
        {
            if(rollback != null) rollback();
        }
    }

    internal sealed class ScopeComposite : Scope
    {
        public ScopeComposite(params Scope[] scopes)
            : base(true)
        {
            this.scopes = scopes;
        }

        Scope[] scopes;

        public override void Commit()
        {
            for (int x = 0, n = scopes.Length; x < n; ++x)
            {
                scopes[x].Commit();
            }
        }

        public override void Dispose()
        {
            for (int x = 0, n = scopes.Length; x < n; ++x)
            {
                scopes[x].Dispose();
            }
        }
    }
}
